package com.cyl.manager.yee.service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.manager.yee.domain.YeeMerchant;
import com.cyl.manager.yee.mapper.YeeMerchantMapper;
import com.cyl.manager.yee.pojo.query.YeeMerchantAdd;
import com.cyl.manager.yee.pojo.query.YeeMerchantQuery;
import com.cyl.pay.dto.xw.WxRwDto;
import com.cyl.yeepay.config.YeePayConfig;
import com.cyl.yeepay.setvice.YeePayMerService;
import com.cyl.yeepay.setvice.YeePayService;
import com.cyl.yeepay.vo.RegxwNotifyRetVo;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.yeepay.yop.sdk.service.mer.model.RegisterQueryV2NetInProgressQueryRespDtoResult;
import com.yeepay.yop.sdk.service.mer.model.RegisterSaasIndexV2UserPreRegisterRespDtoResult;
import com.yeepay.yop.sdk.service.mer.model.RegisterSaasMicroV2ContributeMicroMerchantNetInRespDtoResult;
import com.yeepay.yop.sdk.service.std.model.YopQueryBalanceResponseDTO;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;

/**
 * 商户管理Service业务层处理
 *
 *
 * @author zcc
 */
@Service
public class YeeMerchantService {
    @Autowired
    private YeeMerchantMapper yeeMerchantMapper;

    
    @Autowired
    private YeePayService yeePayService;
    
    @Autowired
    private YeePayConfig yeePayConfig;
    
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private YeePayMerService yeePayMerService;
    
    
    public YeeMerchant addXwShByZtg(YeeMerchant ent) {
    	YeeMerchant yeeMerchant = new YeeMerchant();
		yeeMerchant.setDelFlag(0);
	    yeeMerchant.setCreateTime(LocalDateTime.now());
		yeeMerchant.setDeptZbjId(SecurityUtils.getDeptZbjId());
		yeeMerchant.setCreateBy(SecurityUtils.getUserId());
		yeeMerchant.setApplicationStatus("COMPLETED");
        yeeMerchantMapper.insert(yeeMerchant);
		return yeeMerchant;
	}
    
    /**
     * 查询商户管理
     *
     * @param id 商户管理主键
     * @return 商户管理
     */
    public YeeMerchant selectById(Long id) {
        return yeeMerchantMapper.selectById(id);
    }
    
    /**
     * 查询余额查询
     * @param date
     * @param merchantNo
     * @return
     */
    public  YopQueryBalanceResponseDTO getSysMerchantrAmount(String date) {
    	if(date==null || "".equals(date)) {
    		date = DateUtil.format(DateUtil.date(), "yyyy-MM-dd");
    	}
		String merchantNo = configService.selectConfigByKey("DEFAULT_PAYMENT_ACCOUNT");
		return yeePayService.endBalanceQuery(date, merchantNo);
    }
    
    
    /**
     * 查询余额查询
     * @param date
     * @param merchantNo
     * @return
     */
    public  YopQueryBalanceResponseDTO getMerchantrAmount(String date,String merchantNo) {
    	if(date==null || "".equals(date)) {
    		date = DateUtil.format(DateUtil.date(), "yyyy-MM-dd");
    	}
		return yeePayService.endBalanceQuery(date, merchantNo);
    }
    
    public YeeMerchant getMerchantByNo(String toMerchantNo) {
    	 QueryWrapper<YeeMerchant> queryWrapper = new QueryWrapper<>();
    	 queryWrapper.eq("del_flag",0);
    	 queryWrapper.eq("merchant_no", toMerchantNo);
         return yeeMerchantMapper.selectOne(queryWrapper);

	}
    
    /**
     * 查询商户管理列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 商户管理
     */
    public List<YeeMerchant> selectList(YeeMerchantQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize(),"id desc");
        }
        QueryWrapper<YeeMerchant> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);
        LocalDateTime[] createTimeRange = query.getCreateTimeRange();
        if (createTimeRange != null && createTimeRange.length == 2) {
            LocalDateTime start = createTimeRange[0];
            if (start != null) {
                qw.ge("create_time", start);
            }
            LocalDateTime end = createTimeRange[0];
            if (end != null) {
                qw.le("create_time", end);
            }
        }
        

        String applicationStatus = query.getApplicationStatus();
        if (!StringUtils.isEmpty(applicationStatus)) {
            qw.eq("application_status", applicationStatus);
        }
        
        String merchantMc = query.getMerchantMc();
        if (!StringUtils.isEmpty(merchantMc)) {
            qw.like("merchant_mc", "%".concat(merchantMc.trim()).concat("%"));
        }
        
        
        String merchantFl = query.getMerchantFl();
        if (!StringUtils.isEmpty(merchantFl)) {
            qw.eq("merchant_fl", merchantFl);
        }
        
        String merchantLx = query.getMerchantLx();
        if (!StringUtils.isEmpty(merchantLx)) {
            qw.eq("merchant_lx", merchantLx);
        }
        String merchantNo = query.getMerchantNo();
        if (!StringUtils.isEmpty(merchantNo)) {
            qw.eq("merchant_no", merchantNo);
        }
        String merchantPwd = query.getMerchantPwd();
        if (!StringUtils.isEmpty(merchantPwd)) {
            qw.eq("merchant_pwd", merchantPwd);
        }
        String bankCardType = query.getBankCardType();
        if (!StringUtils.isEmpty(bankCardType)) {
            qw.eq("bank_card_type", bankCardType);
        }
        String accountNo = query.getAccountNo();
        if (!StringUtils.isEmpty(accountNo)) {
            qw.eq("account_no", accountNo);
        }
        String bankCode = query.getBankCode();
        if (!StringUtils.isEmpty(bankCode)) {
            qw.eq("bank_code", bankCode);
        }
        String branchCode = query.getBranchCode();
        if (!StringUtils.isEmpty(branchCode)) {
            qw.eq("branch_code", branchCode);
        }
        String bindId = query.getBindId();
        if (!StringUtils.isEmpty(bindId)) {
            qw.eq("bind_id", bindId);
        }
        Long deptZbjId = query.getDeptZbjId();
        if (deptZbjId != null) {
            qw.eq("dept_zbj_id", deptZbjId);
        }
        return yeeMerchantMapper.selectList(qw);
    }

    /**
     * 新增商户管理
     *
     * @param yeeMerchant 商户管理
     * @return 结果
     */
    public int insert(YeeMerchant yeeMerchant) {
		yeeMerchant.setDelFlag(0);
	    yeeMerchant.setCreateTime(LocalDateTime.now());
		yeeMerchant.setDeptZbjId(SecurityUtils.getDeptZbjId());
		yeeMerchant.setCreateBy(SecurityUtils.getUserId());
		yeeMerchant.setApplicationStatus("COMPLETED");
		if(yeeMerchant!=null) {
			 	YeeMerchant yeeMerchantDB = getMerchantByNo(yeeMerchant.getMerchantNo());
			    if(yeeMerchantDB!=null) {
		           throw new RuntimeException("商户编号["+yeeMerchant.getMerchantNo()+"]，已经存在！");
			    }
		}
        return yeeMerchantMapper.insert(yeeMerchant);
    }

    /**
     * 修改商户管理
     *
     * @param yeeMerchant 商户管理
     * @return 结果
     */
    public int update(YeeMerchant yeeMerchant) {
    	yeeMerchant.setUpdateTime(LocalDateTime.now());
   		yeeMerchant.setUpdateBy(SecurityUtils.getUserId());
   		YeeMerchant yeeMerchantDB = getMerchantByNo(yeeMerchant.getMerchantNo());
	    if(yeeMerchantDB!=null && !yeeMerchant.getId().equals(yeeMerchantDB.getId())) {
           throw new RuntimeException("商户编号["+yeeMerchant.getMerchantNo()+"]，已经存在！");
	    }
	    
        return yeeMerchantMapper.updateById(yeeMerchant);
    }

    /**
     * 批量删除商户管理
     *
     * @param ids 需要删除的商户管理主键
     * @return 结果
     */
    public int deleteByIds(Long[] ids) {
        return yeeMerchantMapper.updateDelFlagByIds(ids);
    }

    /**
     * 删除商户管理信息
     *
     * @param id 商户管理主键
     * @return 结果
     */
    public int deleteById(Long id) {
        Long[] ids = {id};
        return yeeMerchantMapper.updateDelFlagByIds(ids);
    }
    @Transactional
	public YeeMerchant addXwSh(YeeMerchantAdd yeeMerchantAdd) {
		YeeMerchant yeeMerchant = new YeeMerchant(yeeMerchantAdd);
		yeeMerchant.setDelFlag(0);
	    yeeMerchant.setCreateTime(LocalDateTime.now());
		yeeMerchant.setMerchantLx("3");
		yeeMerchant.setDeptZbjId(SecurityUtils.getDeptZbjId());
		yeeMerchant.setCreateBy(SecurityUtils.getUserId());
        String random = RandomUtil.randomNumbers(8);
        String requestNo = "XWSHRW"+DateUtil.format(new Date(), "yyyyMMddHHmmssSSS")+random;
        yeeMerchant.setRequestNo(requestNo);
        yeeMerchantAdd.setRequestNo(requestNo);
        yeeMerchant.setRequestJson(JSONUtil.toJsonStr(yeeMerchantAdd));
        yeeMerchant.setApplicationStatus("REVIEWING");
         yeeMerchantMapper.insert(yeeMerchant);
        RegisterSaasIndexV2UserPreRegisterRespDtoResult dtoResult = yeePayMerService.registerSaasIndexV2(requestNo, yeeMerchantAdd.getMobile(), yeeMerchantAdd.getName(), yeeMerchantAdd.getSfzh());
        yeeMerchant.setReturnJson(JSONUtil.toJsonStr(dtoResult));
        yeeMerchantMapper.updateById(yeeMerchant);
         return yeeMerchant;
	}
 
	
	/**
	 * 修改提现卡
	 * @param id
	 * @return
	 */
    public int updateBankCard(YeeMerchant ent) {
    	YeeMerchant yeeMerchant = yeeMerchantMapper.selectById(ent.getId());
    	yeeMerchant.setAccountNo(ent.getAccountNo());
    	yeeMerchant.setBankCode(ent.getBankCode());
    	yeeMerchant.setBranchCode(ent.getBranchCode());
	    yeeMerchant.setUpdateTime(LocalDateTime.now());

    	if(yeeMerchant.getBindId()!=null && !"".equals(yeeMerchant.getBindId())) {
    		yeePayMerService.updateBankCard(yeeMerchant);
    	}
    	return yeeMerchantMapper.updateById(yeeMerchant);
   }
	
	/**
	 * 修改基本信息 名称和分类
	 * @param id
	 * @return
	 */
    public int updateYeeMerchantJbxx(YeeMerchant ent) {
    	YeeMerchant yeeMerchant = yeeMerchantMapper.selectById(ent.getId());
    	yeeMerchant.setMerchantMc(ent.getMerchantMc());
    	yeeMerchant.setMerchantFl(ent.getMerchantFl());
	    yeeMerchant.setUpdateTime(LocalDateTime.now());
    	return yeeMerchantMapper.updateById(yeeMerchant);
   }
    
	/**
	 * 查询进度
	 * @param id
	 * @return
	 */
    public YeeMerchant registerQueryV2(Long id) {
    	YeeMerchant yeeMerchant = yeeMerchantMapper.selectById(id);
    	if(!"COMPLETED".equals(yeeMerchant.getApplicationStatus())) {
    		String requestNo = yeeMerchant.getRequestNo();
    		RegisterQueryV2NetInProgressQueryRespDtoResult dtoResult = yeePayMerService.registerQueryV2(requestNo);
    		String aStatus = dtoResult.getApplicationStatus();
    		if(aStatus.equals("COMPLETED")) {
    			yeeMerchant.setMerchantNo(dtoResult.getMerchantNo());
    			Long bindId = yeePayMerService.addBankCard(yeeMerchant);
    			yeeMerchant.setBindId(bindId+"");
    		}
    		yeeMerchant.setApplicationStatus(dtoResult.getApplicationStatus());
    		yeeMerchant.setRwjdcxReturnJson(JSONUtil.toJsonStr(dtoResult));
    		yeeMerchant.setUpdateTime(LocalDateTime.now());
    		yeeMerchantMapper.updateById(yeeMerchant);
    	}
    	return yeeMerchant;
   }

	public void notify(RegxwNotifyRetVo regxwNotifyRetVo,String json) {
		QueryWrapper<YeeMerchant> qw = new QueryWrapper<>();
        qw.eq("request_no",regxwNotifyRetVo.getRequestNo());
		YeeMerchant yeeMerchant = yeeMerchantMapper.selectOne(qw);
		yeeMerchant.setMerchantNo(regxwNotifyRetVo.getMerchantNo());
		yeeMerchant.setUpdateTime(LocalDateTime.now());
		yeeMerchant.setRwjdcxReturnJson(json);
		yeeMerchant.setApplicationStatus(regxwNotifyRetVo.getApplicationStatus());
		yeeMerchant.setMerchantNo(regxwNotifyRetVo.getMerchantNo()); 
		yeeMerchantMapper.updateById(yeeMerchant);
		
	}

	
    public YeeMerchant registerSaasMicroV2(YeeMerchant yeeMerchant) {
    	
    	Map<String, Object> params = yeeMerchant.getParams();
//    	"legalLicenceFrontUrl":"法人证件人像面照片地址", 
//    	"legalLicenceBackUrl":"法人证件非人像面照片地址",
//   	"province":"经营省",
//  	"city":"经营市", 
// 	    "district":"经营区", 
//	    "address":"经营地址"
    	
//    	"province": "重庆市",
//        "city": "重庆市",
//        "district": "北碚区",
//        "address": "1123123ZSZZ",
//        "legalLicenceFrontUrl": "http://staticres.yeepay.com/jcptb-merchant-netinjt05/2025/03/22/merchant-1742650431714-4f9cb7b5-09ca-4c17-a1af-bc3a29f65eda-fadLiWBVmVrrwxxMTGxn.png",
//        "legalLicenceBackUrl": "http://staticres.yeepay.com/jcptb-merchant-netinjt05/2025/03/22/merchant-1742650434632-972820db-bd29-4e38-9eee-2ebde3507e52-yXzNWnJfoCUDnuNLEayd.png"
//        	
        	
    	LinkedHashMap<String, Object> merchantSubjectInfo = new LinkedHashMap<String, Object>();
    	merchantSubjectInfo.put("signName", yeeMerchant.getMerchantMc());
    	merchantSubjectInfo.put("shortName", yeeMerchant.getMerchantMc());

    	// 商户法人信息 { "legalLicenceType":"法人证件类型", "legalLicenceNo":"法人证件编号", 

//    	"mobile":"法人手机号" }
    	LinkedHashMap<String, Object> merchantCorporationInfo = new LinkedHashMap<String, Object>();
    	merchantCorporationInfo.put("legalLicenceType", "ID_CARD");
    	merchantCorporationInfo.put("legalLicenceNo", yeeMerchant.getSfzh());
    	merchantCorporationInfo.put("mobile", yeeMerchant.getMobile());
    	merchantCorporationInfo.put("legalLicenceFrontUrl", params.get("legalLicenceFrontUrl"));
    	merchantCorporationInfo.put("legalLicenceBackUrl", params.get("legalLicenceBackUrl"));
    	
    	 
    	
    	
    	//  { "province":"经营省", "city":"经营市", "district":"经营区", "address":"经营地址" }
    	LinkedHashMap<String, Object> businessAddressInfo = new LinkedHashMap<String, Object>();
    	businessAddressInfo.put("province", params.get("province"));
    	businessAddressInfo.put("city", params.get("city"));
    	businessAddressInfo.put("district",params.get("district"));
    	businessAddressInfo.put("address", params.get("address"));
    	
    
    	//结算账户信息  { "bankAccountType":"银行账户类型", "bankCardNo":"银行账户号码", "bankCode":"开户总行编码" }
    	LinkedHashMap<String, Object> accountInfo = new LinkedHashMap<String, Object>();
    	accountInfo.put("bankAccountType", yeeMerchant.getBankCardType());
    	accountInfo.put("bankCardNo", yeeMerchant.getAccountNo());
    	accountInfo.put("bankCode", yeeMerchant.getBankCode());
        String random = RandomUtil.randomNumbers(8);
        String requestNo = "XWSHRW"+DateUtil.format(new Date(), "yyyyMMddHHmmssSSS")+random;

    	WxRwDto rw  = new WxRwDto(requestNo, merchantSubjectInfo, merchantCorporationInfo, businessAddressInfo, accountInfo, params);
    	RegisterSaasMicroV2ContributeMicroMerchantNetInRespDtoResult dtoResult  = yeePayMerService.registerSaasMicroV2(rw);
    	
    	yeeMerchant.setApplicationStatus(dtoResult.getApplicationStatus());
    	yeeMerchant.setRequestNo(requestNo);
    	yeeMerchant.setDelFlag(0);
	    yeeMerchant.setCreateTime(LocalDateTime.now());
		yeeMerchant.setDeptZbjId(SecurityUtils.getDeptZbjId());
		yeeMerchant.setCreateBy(SecurityUtils.getUserId());
		yeeMerchant.setRequestJson(JSONUtil.toJsonStr(rw));
    	yeeMerchant.setReturnJson(JSONUtil.toJsonStr(dtoResult));
        yeeMerchantMapper.insert(yeeMerchant);    	
		return yeeMerchant;
    }
	

	
}
